var json = require("json");
var string  = require("string");
var root = [];
var links = [];

var address = 0;
var linkAddress = 0;

function checkValType(val, prop){
	if(typeof(val) == typeof(prop.value))
		return true;
	return false;
}

function setName(val, name){
	string.copy(val.name, name);
}

function setValue(val, value){
	string.copy(val.value, value);
}

function setType(val, type){
	string.copy(val.type, type);
}

function setAddr(val, addr){
	string.copy(val.addr, addr);
}

function createValue(name, value){
	var val = {};
	val.name = string.alloc(20);
	setName(val, name);
	val.value = value;
	return val;
}

function createLink(sc, ss, tc, ts){
	var localLink = {};
	localLink.sc = sc;
	localLink.ss = string.alloc(20);
	string.copy(localLink.ss, ss);
	localLink.tc = tc;
	localLink.ts = string.alloc(20);
	string.copy(localLink.ts, ts);
	
	links.push(localLink);
	return localLink;
}

function createRawComp(name, type, addr){
	var comp = {};
	comp.name = string.alloc(20);
	setName(comp, name);
	comp.type = string.alloc(20);
	setType(comp, type);
	comp.addr = addr;
	comp.props = [];
	
	address++;
	root.push(comp);
	return comp;
}

function createComp(name, type, addr){
	var comp = {};
	comp.name = string.alloc(20);
	setName(comp, name);
	comp.type = string.alloc(20);
	setType(comp, type);
	comp.addr = addr;
	comp.props = [];
	
	comp.props.push(createValue("wsX", 0));
	comp.props.push(createValue("wsY", 0));
	
	address++;
	root.push(comp);
	return comp;
}

function findProp(addr, name){
	var i = 0;
	var j = 0;
	while(i < root.length()){
		var comp = root[i];
		if(comp.addr == addr){
			j = 0;
			while(j < comp.props.length()){
				var prop = comp.props[j];
				if(prop.name == name)
					return prop;
				j++;
			}
		}
		i++;
	}
	return undefined;
}

function findPropByComp(comp, name){
	var j = 0;
	while(j < comp.props.length()){
		var prop = comp.props[j];
		if(prop.name == name)
			return prop;
		j++;
	}
	return undefined;
}

function findComp(addr, name){
	var i = 0;
	var j = 0;
	while(i < root.length()){
		var comp = root[i];
		if(comp.addr == addr && comp.name == name){
			return comp;
		}
		i++;
	}
	return undefined;
}

var adcPoint = createComp("adc", "DJsdNumericPoint", address);
adcPoint.props.push(createValue("out", 0));
